import axios from 'axios';
import {Message} from "element-ui";

axios.interceptors.response.use(resp=>{
    if(resp.status==200 && resp.data && resp.data.status==500){
        if(resp.data.msg){
            Message.error({message:resp.data.msg});
            return;
        }
    }
    if(resp.data.msg){
        Message.success({message:resp.data.msg});
    }
    return resp.data;
},error => {
    if(error.response){
        if(error.response.status==404 || error.response.status==504){
            Message.error({message:'服务器被吃了o(╯□╰)o'});
        }else if(error.response.status==403){
            Message.error({message:'对不起，权限不足!'});
        }else if(error.response.status==401){
            Message.error({message:'对不起，没有登陆!'});
        }else if(error.response.status==400){
            Message.error({message:'对不起，参数有误!'});
        }else if(error.response.status==405){
            Message.error({message:'对不起，请求方式有误!'});
        }else{
            Message.error({message:'未知错误!'});
        }
    }
    return;
})

let base='';

export const getRequest=(url,params)=>{
    return axios({
        method:'get',
        data:params,
        url:`${base}${url}`
    })
}

export const postRequest=(url,params)=>{
    return axios({
        method:'post',
        data:params,
        url:`${base}${url}`
    })
}

export const postKeyValueRequest=(url,params)=>{
    return axios({
        method:'post',
        data:params,
        url:`${base}${url}`,
        transformRequest:[
            function (data) {
                let result='';
                for(let i in data){
                    result+=encodeURIComponent(i)+'='+encodeURIComponent(data[i])+'&';
                }
                return result;
            }
        ],
        header:{
            'Content-Type':'application/x-www-form-urlencoded'
        }
    })
}

export const putRequest=(url,params)=>{
    return axios({
        method:'put',
        data:params,
        url:`${base}${url}`
    })
}

export const deleteRequest=(url,params)=>{
    return axios({
        method:'delete',
        data:params,
        url:`${base}${url}`
    })
}